<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="渠道名称" prop="channelName">
            <el-input v-model="queryParams.channelName" placeholder="请输入" clearable style="width: 120px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入" clearable style="width: 120px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="业务类型" prop="serviceType">
            <el-select v-model="queryParams.serviceType" placeholder="请选择">
              <el-option v-for="dict in dict.type.channel_service_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择">
              <el-option v-for="dict in dict.type.channel_channel_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="渠道类型" prop="channelType">
            <el-select v-model="queryParams.channelType" placeholder="请选择">
              <el-option v-for="dict in dict.type.channel_channel_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns" />
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="渠道编号" align="center" prop="id" />

          <el-table-column label="状态" align="center" key="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.channel_channel_status" :value="scope.row.channelStatus" />
            </template>
          </el-table-column>
          <el-table-column label="渠道名称(简称)" align="center" key="channelName" prop="channelName" />
          <el-table-column label="联系人" align="center" key="linkman" prop="linkman" />
          <el-table-column label="联系人手机" align="center" key="phoneNum" prop="phoneNum" width="120" />
          <el-table-column label="业务类型" align="center" key="serviceType" prop="serviceType">
            <template slot-scope="scope">
              <p v-if="scope.row.serviceType == 'house'">
                房贷
              </p>
              <p v-else-if="scope.row.serviceType == 'car'">
                车贷
              </p>
              <p v-else>
                信贷
              </p>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="admin.nickName" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <!-- v-if="scope.row.channelStatus == 'y' disabled='true'" -->
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope" v-if="scope.row.id != undefined">
              <el-button size="mini" type="text" icon="el-icon-view" @click="checkInfo(scope.row)">查看</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button size="mini" type="text" icon="el-icon-switch-button"
                v-if="scope.row.channelStatus == 'n' || scope.row.channelStatus == 'b'"
                @click="updateStatus(scope.row)">启用
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-switch-button" v-if="scope.row.channelStatus == 'y'"
                @click="banThisChannel(scope.row)">禁用
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 查看渠道具体信息的弹出框 -->
    <el-dialog title="资金渠道信息" :visible.sync="channelDialogStatus" width="1366px" append-to-body>
      <el-form ref="particularsForm" :model="particularsForm" :rules="rules" label-width="80px">
        <!-- 渠道商信息 -->
        <el-row>
          <el-col :span="24" style="height: 42px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="background-color: azure;">
              渠道商信息
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="渠道名称" prop="channelName">
              <el-input :disabled="true" v-model="particularsForm.channelName" placeholder="请输入渠道名称" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="渠道简称" prop="deptId">
              <el-input :disabled="true" v-model="particularsForm.channelSimpleName" placeholder="请输入简称，用于推广"
                maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="公司全称" prop="companyName">
              <el-input :disabled="true" v-model="particularsForm.companyName" placeholder="请输入公司全称" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="业务类型" prop="serviceType">
              <el-select :disabled="true" v-model="particularsForm.serviceType" placeholder="请选择" maxlength="30"
                width="360px">
                <el-option v-for="dict in dict.type.channel_service_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>


          </el-col>
        </el-row>

        <!-- 管理员信息 -->
        <el-row>
          <el-col :span="24" style="height: 42px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="background-color: azure;">
              管理员信息
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="渠道管理员账号" label-width="120px">
              <el-input :disabled="true" v-model="particularsForm.admin.userName" placeholder="请输入管理员账号" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="联系人姓名" label-width="100px">
              <el-input :disabled="true" v-model="particularsForm.admin.nickName" placeholder="请输入真实姓名" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="联系人身份证" label-width="120px">
              <el-input :disabled="true" v-model="particularsForm.admin.citizenIdentity" placeholder="请输入身份证号码"
                maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="联系人手机号" label-width="100px">
              <el-input :disabled="true" v-model="particularsForm.admin.phoneNumber" placeholder="请输入手机号" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 银行账号信息 -->
        <el-row>
          <el-col :span="24" style="height: 42px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="background-color: azure;">
              银行账号信息
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="收款人姓名" prop="beneficiaryName" label-width="100px">
              <el-input :disabled="true" v-model="particularsForm.beneficiaryName" placeholder="请输入真实姓名" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="收款银行卡号" prop="beneficiaryCardId" label-width="120px">
              <el-input :disabled="true" v-model="particularsForm.beneficiaryCardId" placeholder="请输入银行卡号"
                maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="开户银行" prop="beneficiaryBank" label-width="100px">
              <el-input :disabled="true" v-model="particularsForm.beneficiaryBank" placeholder="请输入银行名称" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item :disabled="true" label="开户行支行" prop="beneficiarySubBank" label-width="120px">
              <el-input :disabled="true" v-model="particularsForm.beneficiarySubBank" placeholder="请输入开户银行支行名称"
                maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="银行预留手机号" prop="bankcardPhone" label-width="120px">
              <el-input :disabled="true" v-model="particularsForm.bankcardPhone" placeholder="请输入与银行卡绑定的手机号"
                maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="height: 100px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="height: 38px;background-color: azure;">
              关联产品
            </div>
          </el-col>
        </el-row>
        <!-- 查看界面显示关联产品 -->
        <el-row>
          <el-col>
            <el-table v-loading="loading" :data="relativeProductsList">
              <el-table-column label="产品ID" align="center" prop="productionCode" width="400px" />
              <el-table-column label="产品名称" align="center" prop="productionName" width="400px" />
              <el-table-column label="产品状态" align="center" prop="productionType" width="500px">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.production_info_production_status" :value="scope.row.productionStatus" />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="updateDetailStatus">启 用</el-button>
        <el-button @click="cancelCheckInfo">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加资金方产品" :visible.sync="productFormStatus" width="800px" append-to-body>
      <el-form ref="productForm" :model="productForm" :rules="rules" label-width="80px">
        <!-- 渠道商信息 -->
        <el-row>
          <el-col :span="18">
            <el-input v-model="productForm.searchInfo" placeholder="请输入产品ID或名称查询" maxlength="30" width="240px"
              style="height: 10px;" />
          </el-col>
          <el-col :span="6">
            <el-button @click="searchRelationProduct" type="primary" size="small" style="margin-left: 20px;">
              查询
            </el-button>
          </el-col>
        </el-row>
        <!-- <el-divider></el-divider> -->
        <el-row style="margin-top: 20px;">
          <el-col>
            <el-table v-loading="loading" :data="productsList">

              <el-table-column label="产品编号" align="center" prop="productionCode" />
              <el-table-column label="产品名称" align="center" prop="productionName" />
              <el-table-column label="产品类型" align="center" prop="productionType" width="120">
                <template slot-scope="scope">
                  <p v-if="scope.row.productionType == 'house'">
                    房贷
                  </p>
                  <p v-else-if="scope.row.productionType == 'car'">
                    车贷
                  </p>
                  <p v-else>
                    信贷
                  </p>
                </template>
              </el-table-column>
              <el-table-column label="产品发布方" align="center" prop="productionProducer" width="120" />
              <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.productionId != undefined">
                  <el-button size="mini" type="text" icon="el-icon-folder-add" @click="addProduction(scope.row)">添加
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="productionTotal>0" :total="productionTotal" :page.sync="productPageParams.pageNum"
              :limit.sync="productPageParams.pageSize" @pagination="getAllCaptitalProducts" />
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>


    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1366px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 渠道商信息 -->
        <el-row>
          <el-col :span="24" style="height: 42px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="background-color: azure;">
              渠道商信息
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="渠道名称" prop="channelName">
              <el-input v-model="form.channelName" placeholder="请输入渠道名称" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="渠道简称" prop="channelSimpleName">
              <el-input v-model="form.channelSimpleName" placeholder="请输入简称，用于推广" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="公司全称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入公司全称" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="业务类型" prop="serviceType">
              <el-select v-model="form.serviceType" placeholder="请选择" maxlength="30" width="360px">
                <el-option v-for="dict in dict.type.channel_service_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>


          </el-col>
        </el-row>

        <!-- 管理员信息 -->
        <el-row style="margin-top: 20px;">
          <el-col :span="24" style="height: 42px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="background-color: azure;">
              管理员信息
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="渠道管理员账号" label-width="120px">
              <!-- <el-input v-model="form.admin.userName" placeholder="请输入管理员账号" maxlength="30" width="360px" /> -->
              <sys-admin @selectedAdminChange="handleSelectedAdminChange"></sys-admin>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="联系人姓名" label-width="100px">
              <el-input v-model="form.admin.nickName" :disabled="true" placeholder="请输入真实姓名" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="联系人身份证" label-width="120px">
              <el-input v-model="form.admin.citizenIdentity" :disabled="true" placeholder="请输入身份证号码" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="联系人手机号" label-width="100px">
              <el-input v-model="form.admin.phoneNumber" :disabled="true" placeholder="请输入手机号" maxlength="30"
                width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 银行账号信息 -->
        <el-row style="margin-top: 20px;">
          <el-col :span="24" style="height: 42px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="background-color: azure;">
              银行账号信息
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="收款人姓名" prop="beneficiaryName" label-width="100px">
              <el-input v-model="form.beneficiaryName" placeholder="请输入真实姓名" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="收款银行卡号" prop="beneficiaryCardId" label-width="120px">
              <el-input v-model="form.beneficiaryCardId" placeholder="请输入银行卡号" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="开户银行" prop="beneficiaryBank" label-width="100px">
              <el-input v-model="form.beneficiaryBank" placeholder="请输入银行名称" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="开户行支行" prop="beneficiarySubBank" label-width="120px">
              <el-input v-model="form.beneficiarySubBank" placeholder="请输入开户银行支行名称" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-top: 10px;">
          <el-col :span="8" style="margin-left: 100px; height: 42px;">
            <el-form-item label="银行预留手机号" prop="bankcardPhone" label-width="120px">
              <el-input v-model="form.bankcardPhone" placeholder="请输入与银行卡绑定的手机号" maxlength="30" width="360px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="this.title!='添加资金方渠道'" style="margin-top: 20px;">
          <el-col :span="24" style="height: 100px; letter-spacing: 1px; text-indent: 20px;">
            <div class="grid-content bg-purple-light" style="height: 38px;background-color: azure;">
              关联产品
              <el-button @click="addRelationProduct" type="primary" size="mini"
                style='position: absolute;right:10px;top:5px;'>
                添加关联产品
              </el-button>
            </div>
          </el-col>
        </el-row>

        <el-row v-if="this.title!='添加资金方渠道'">
          <el-col>
            <el-table v-loading="loading" :data="relativeProductsList">
              <el-table-column label="产品ID" align="center" prop="productionCode" width="400px" />
              <el-table-column label="产品名称" align="center" prop="productionName" width="300px" />
              <el-table-column label="产品状态" align="center" prop="productionType" width="300px">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.production_info_production_status" :value="scope.row.productionStatus" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.productionId != undefined">
                  <el-button size="mini" type="text" icon="el-icon-folder-add"
                    @click="removeRelativeProduction(scope.row)">取消关联
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="24" style="height: 20px;">
            <el-button style="position: absolute;right:750px;top:0px;" type="primary" @click="submitForm">保 存
            </el-button>
            <el-button style="position: absolute;right:600px;top:0px;" @click="cancel">取 消</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import {
  listCapitalChannel, searchCapitalChannel, addCapitalChannel, findCurrentUser,
  updateChannelStatus, checkChannelInfo, updateCapitalChannel, getAllUserInfo
} from "@/api/capitalChannel";
import { banChannel, getAllRelativeProducts, listCapitalProductions, searchRelProduct, addProductToChannel, deleteRelProduct } from "@/api/assetChannel";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Dict from "../../system/dict/index.vue";
import DictTag from "../../../components/DictTag/index.vue";
import SysAdmin from "../../../components/SysAdmin/index.vue"

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'channel_channel_status', 'channel_service_type', 'channel_channel_type','production_info_production_status'],
  components: { Treeselect, Dict, DictTag, SysAdmin },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      allUserInfo: [],
      //关联产品
      productFormStatus: false,
      productPageParams: {
        pageNum: 1,
        pageSize: 10
      },
      productsList: null,
      productionTotal: 0,
      productForm: {
        searchInfo: ''
      },
      // 表单参数
      form: {
        channelName: '',
        channelSimpleName: '',
        companyName: '',
        serviceType: '',
        beneficiaryName: '',
        beneficiaryCardId: '',
        beneficiaryBank: '',
        beneficiarySubBank: '',
        bankcardPhone: '',
        admin: {
          userId: undefined,
          userName: undefined,
          nickName: undefined,
          citizenIdentity: undefined,
          phoneNumber: undefined
        }
      },
      particularsForm: {
        id: '',
        channelName: '',
        channelSimpleName: '',
        companyName: '',
        serviceType: '',
        beneficiaryName: '',
        beneficiaryCardId: '',
        beneficiaryBank: '',
        beneficiarySubBank: '',
        bankcardPhone: '',
        admin: {
          userId: undefined,
          userName: undefined,
          nickName: undefined,
          citizenIdentity: undefined,
          phoneNumber: undefined
        }
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      availableUsersOption: [{
        value: '选项1',
        label: '黄金糕'
      }],
      currentUser: this.$store.state.user,
      currentUserInfo: {},
      //关联产品数据
      relativeProductsList: [],
      channelAdmin: {
        userName: undefined,
        nickName: undefined,
        citizenIdentity: undefined,
        phoneNum: undefined
      },

      channelDialogStatus: false,
      buttonDisabled: false,

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channelName: "",
        phonenumber: "",
        serviceType: "",
        status: "",
        channelType: ""
      },
      data: {
        ids: this.ids,
        channelType: "capitalChannel"
      },
      searchFields: {
        channelName: "",
        phonenumber: "",
        serviceType: "",
        status: "",
        channelType: ""

      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        channelName: [
          { required: true, message: "渠道名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '渠道名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        channelSimpleName: [
          { required: true, message: "渠道简称不能为空", trigger: "blur" },
          { min: 2, max: 30, message: '渠道名称长度必须介于 2 和 30 之间', trigger: 'blur' }
        ],
        companyName: [
          { required: true, message: "公司全称不能为空", trigger: "blur" },
          { min: 5, max: 30, message: '公司全称长度必须介于 5 和 30 之间', trigger: 'blur' }
        ],
        beneficiaryName: [
          { required: true, message: "收款人姓名不能为空", trigger: "blur" },
          { min: 2, max: 10, message: '收款人姓名必须介于 2 和 10 之间', trigger: 'blur' }
        ],
        beneficiaryCardId: [
          { required: true, message: "收款银行卡号不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]{1}(?:\d{15}|\d{18})$/,
            message: "请输入正确的银行卡号",
            trigger: "blur"
          }
        ],
        beneficiaryBank: [
          { required: true, message: "开户银行名称不能为空", trigger: "blur" },
          { min: 2, max: 10, message: '开户银行名称必须介于 2 和 10 之间', trigger: 'blur' }
        ],
        beneficiarySubBank: [
          { required: true, message: "开户行支行名称不能为空", trigger: "blur" },
          { min: 5, max: 30, message: '开户行支行名称必须介于 5 和 30 之间', trigger: 'blur' }
        ],
        bankcardPhone: [
          { required: true, message: "银行预留手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    ids(newVal) {
      this.data.ids = newVal;
    }
  },
  created() {
    this.getList();
    this.getCurrentUserInfo();
    this.getAllUser();
    this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    getAllUser() {
      getAllUserInfo().then(response => {
        console.log("所有用户的信息", response)
        this.allUserInfo = response.data;
      }).catch();
    },

    handleSelectedAdminChange(val) {
      // console.log('当前选择的管理员信息',val)
      let temp = this.allUserInfo
      if (temp instanceof Array) {
        temp.forEach(element => {
          if (element.userId == val) {
            for (const key in this.form.admin) {
              this.form.admin[key] = element[key]
            }
          }
        });
      }
    },

    checkInfo(data) {
      this.reset();
      checkChannelInfo(data.id).then(response => {
        console.log(response)
        this.particularsForm = response.data;
      }).catch();
      getAllRelativeProducts(data.id).then(response => {
        console.log('渠道相关产品信息', response)
        this.relativeProductsList = response.data;
      }).catch();
      if (this.channelDialogStatus == false) {
        this.channelDialogStatus = true;
      }
    },

    rewriteCheckInfo(channelId) {
      this.reset();
      if (this.title == '' || this.title == '添加资金方渠道') {
        this.title = "编辑资金方渠道";
      }
      checkChannelInfo(channelId).then(response => {
        this.form = response.data;
      }).catch();
      getAllRelativeProducts(channelId).then(response => {
        this.relativeProductsList = response.data;
      }).catch();
      if (this.open == false) {
        this.open = true;
      }
    },

    cancelCheckInfo() {
      this.channelDialogStatus = false;
      this.reset();
    },

    addRelationProduct() {
      this.getAllCaptitalProducts();
      this.productFormStatus = true;
    },

    removeRelativeProduction(row) {
      deleteRelProduct(row.cpmId).then(response => {
        if (response.code == 200) {
          this.$notify({
            message: response.msg,
            type: 'success'
          });
          this.rewriteCheckInfo(this.form.id);
        } else {
          this.$notify({
            message: response.msg,
            type: 'warning'
          });
        }
      }).catch();
    },

    getAllCaptitalProducts() {
      listCapitalProductions(this.productPageParams.pageNum, this.productPageParams.pageSize).then(response => {
        console.log("所有资金渠道产品的信息", response)
        this.productsList = response.rows
        this.productionTotal = response.total
      }).catch();
    },

    searchRelationProduct() {
      searchRelProduct(this.productForm).then(response => {
        console.log("查询到的产品", response)
        if (response.code == 200) {
          this.$notify({
            message: response.msg,
            type: 'success'
          });
          this.productsList = response.data;
          this.productForm.searchInfo = '';
        } else {
          this.$notify({
            message: response.msg,
            type: 'warning'
          });
        }
      }).catch();
    },

    addProduction(row) {
      let data = {
        productionId: row.productionId,
        channelId: this.form.id
      }
      addProductToChannel(data).then(response => {
        if (response.code == 200) {
          this.$notify({
            message: response.msg,
            type: 'success'
          });
          this.productFormStatus = false;
          this.rewriteCheckInfo(data.channelId);
        } else {
          this.$notify({
            message: response.msg,
            type: 'warning'
          });
        }
      }).catch();
    },

    /** 查询资金渠道状态 */
    updateStatus(data) {
      // console.log(data)
      updateChannelStatus(data.id).then(response => {
        this.getList();
      }).catch();
    },

    banThisChannel(data) {
      banChannel(data.id).then(response => {
        this.getList();
      }).catch();
    },

    updateDetailStatus() {
      console.log("当前渠道详情数据", this.particularsForm)
      updateChannelStatus(this.particularsForm.id).then(response => {
        this.channelDialogStatus = false;
        this.getList();
      }).catch();
    },

    /** 查询资金渠道列表 */
    getList() {
      this.loading = true;

      listCapitalChannel(this.queryParams.pageNum, this.queryParams.pageSize).then(response => {
        console.log("请求所有资金渠道", response);
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch();
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form.channelName = undefined,
        this.form.channelSimpleName = undefined,
        this.form.companyName = undefined,
        this.form.serviceType = undefined,
        this.form.beneficiaryName = undefined,
        this.form.beneficiaryCardId = undefined,
        this.form.beneficiaryBank = undefined,
        this.form.beneficiarySubBank = undefined,
        this.form.bankcardPhone = undefined
      this.form.admin.userId = undefined;
      this.form.admin.userName = undefined;
      this.form.admin.nickName = undefined;
      this.form.admin.citizenIdentity = undefined;
      this.form.admin.phoneNumber = undefined;

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      searchCapitalChannel(this.queryParams).then(response => {
        console.log("查询出所有资金渠道", response);
        this.loading = true;
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if (this.title == '' || this.title == '编辑资金方渠道') {
        this.title = '添加资金方渠道';
      }
      this.form.admin.userId = this.currentUserInfo.userId
      this.form.admin.userName = this.currentUserInfo.userName
      this.form.admin.nickName = this.currentUserInfo.nickName
      this.form.admin.phoneNumber = this.currentUserInfo.phoneNumber
      this.form.admin.citizenIdentity = this.currentUserInfo.citizenIdentity
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(data) {
      this.reset();
      if (this.title == '' || this.title == '添加资金方渠道') {
        this.title = "编辑资金方渠道";
      }

      checkChannelInfo(data.id).then(response => {
        console.log(response)
        this.form = response.data;
      }).catch();
      getAllRelativeProducts(data.id).then(response => {
        console.log('渠道相关产品信息', response)
        this.relativeProductsList = response.data;
      }).catch();
      this.open = true;
    },
    getCurrentUserInfo() {
      findCurrentUser(this.currentUser.name).then(response => {
        console.log("当前用户信息", response)
        this.currentUserInfo = response.data
      }).catch();
    },

    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => { });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {

          if (this.title == '添加资金方渠道') {
            if (this.form.channelName != undefined) {
              addCapitalChannel(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            updateCapitalChannel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });

    },
    /** 导出按钮操作 */
    handleExport() {
      console.log("选中的行ID集合:", this.data);
      this.download('channel/exportChosen', this.data, `资金渠道信息列表_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>